﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SunTzu.Core.Authorization;
using Odyssey.Linq;
using SunTzu.Utility;

namespace Rea.Web.Models
{
    public class LoginHelper
    {
        const string CURRENT_USER = "CurrentUser";
        public static tb_account CurrentUser
        {
            get
            {
                var user = HttpContext.Current.Session[CURRENT_USER] as tb_account;
                return user ?? new tb_account();
            }
            set
            {
                HttpContext.Current.Session[CURRENT_USER] = value;
            }
        }

        #region IAuthorization Members

        public static bool Login(string email, string password)
        {
            var db = DataContextManager.GetContext();
            var user = db.tb_accounts.FirstOrDefault(c => c.Email == email
                && c.Password == Encryption.MD5Encrypt(password));
            if (user != null)
            {
                CurrentUser = user;
                return true;
            }
            return false; ;
        }

        public static bool IsLogin
        {
            get { return CurrentUser.Id > 0; }
        }

        /// <summary>
        /// 是否是网管用户
        /// </summary>
        public static bool IsAdmin
        {
            get { return false; }
        }

        ///// <summary>
        ///// 是否是超管用户
        ///// </summary>
        //public bool IsSuperAdmin
        //{
        //    get { return CurrentUser.RoleId == 3; }
        //}

        public static bool HasAuthority(string authorCode)
        {
            return true;
        }

        //public bool HasAuthority(int authorCode)
        //{
        //    return CurrentUser.RoleId >= authorCode;
        //}

        public static void Logout()
        {
            HttpContext.Current.Session.Clear();
        }

        public static int CurrentUserId
        {
            get { return CurrentUser.Id; }
        }

        public static string CurrentUserName
        {
            get { return CurrentUser.Name; }
        }

        #endregion

        public static void Refresh()
        {
            CurrentUser = DataContextManager.GetContext().tb_accounts.FirstOrDefault(c => c.Id == CurrentUserId);
        }

        public static tb_account GetCurrentUser()
        {
            var user = HttpContext.Current.Session[CURRENT_USER] as tb_account;
            return user ?? new tb_account();
        }
    }
}